package a02_链表;

/**
 * <p>
 * a03_设计链表复习5
 * </p>
 *
 * @author flyduck
 * @since 2024/12/30
 */
public class a03_设计链表复习5 {

    public static void main(String[] args) {
        a03_设计链表复习5 test = new a03_设计链表复习5();
        test.addAtHead(1);
        test.addAtTail(3);
        test.addAtIndex(1,2);

    }

    private ListNode dummyNode;
    private int size;

    public a03_设计链表复习5() {
        dummyNode = new ListNode(0);
        size = 0;
    }

    public int get(int index) {
        if(index < 0 || index >= this.size){
            return -1;
        }
        ListNode currentNode = dummyNode;
        while (index + 1 > 0) {//假设index=0 0+1>0进去一次
            currentNode = currentNode.next;
            index--;
        }
        return currentNode.val;
    }

    public void addAtHead(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = dummyNode.next;
        dummyNode.next = newNode;
        size++;
    }

    public void addAtTail(int val) {
        ListNode currentNode = dummyNode;
        while (currentNode.next != null) {
            currentNode = currentNode.next;
        }
        ListNode newNode = new ListNode(val);
        currentNode.next = newNode;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size){
            return;
        }
        ListNode currentNode = dummyNode;
        while (index > 0) {//index=0，不进入循环
            currentNode = currentNode.next;
            index--;
        }

        ListNode newNode = new ListNode(val);
        newNode.next = currentNode.next;
        currentNode.next = newNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size){
            return;
        }

        ListNode currentNode = dummyNode;
        while (index > 0) {//index=0，不进入循环
            currentNode = currentNode.next;
            index--;
        }
        currentNode.next = currentNode.next.next;
        size--;
    }
}
